package com.xizi.lotterySystem.utils;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    private static Logger log = LoggerFactory.getLogger(RedisUtil.class);

    public static StringRedisTemplate redisTemplate ;// 静态副本

    @Autowired
    private StringRedisTemplate instanceRedisTemplate; // 实例字段接收注入

    // 初始化静态副本
    @PostConstruct
    public void init() {
        redisTemplate = this.instanceRedisTemplate;
    }


    public static boolean set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e) {
            log.error("set({}) + e {}",(key + value),e.getMessage());
            return false;
        }
    }

    public static boolean set(String key, String value,Long time) {
        try {
            redisTemplate.opsForValue().set(key, value,time, TimeUnit.SECONDS);
            return true;
        }catch (Exception e){
            log.error("set({})",(key + ", " +  value),e);
            return false;
        }
    }

    public static String get(String key) {
        try {
            return redisTemplate.opsForValue().get(key);
        }catch (Exception e){
            log.error("get({}) e {}",key,e.getMessage());
            return null;
        }
    }

    public static boolean del(String key) {
        if(!StringUtils.hasText(key)){
            return false;
        }
        try {
            return redisTemplate.delete(key);
        }catch (Exception e){
            log.error("del({}) e {}",key,e.getMessage());
            return false;
        }
    }

    public static boolean hasKey(String key) {
        if(!StringUtils.hasText(key)){
            return false;
        }
        try {
            return redisTemplate.hasKey(key);
        }catch (Exception e){
            log.error("hasKey({}) e {}",key,e.getMessage());
            return false;
        }
    }
}
